package com.atshangluo.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atshangluo.servicebase.exceptionHandler.EduException;
import com.atshangluo.eduservice.entity.EduSubject;
import com.atshangluo.eduservice.entity.vo.ExcelSubjectData;
import com.atshangluo.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName SubjectListen.java
 * @Description TODO
 * @createTime 2021年07月26日 18:09:00
 */
public class SubjectListen extends AnalysisEventListener<ExcelSubjectData> {


    public EduSubjectService service;

    public SubjectListen() {
    }

    public SubjectListen(EduSubjectService service) {
        this.service = service;
    }



    // 一行一行读取excel内容
    @Override
    public void invoke(ExcelSubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData==null){
            throw new EduException(20001,"文件数据为空");
        }else {

            // 一行一行读取，第一个值一级分类，第二个值二级分类
            // 判断一级分类是否重复
            EduSubject oneNoRepeat = this.oneNoRepeat(service, subjectData.getOneSubjectName());
            if (oneNoRepeat==null){  // 没有相同的，可以添加

                oneNoRepeat = new EduSubject();
                oneNoRepeat.setParentId("0");
                oneNoRepeat.setTitle(subjectData.getOneSubjectName());
                service.save(oneNoRepeat);

            }


            String parentId = oneNoRepeat.getId();
            EduSubject twoNoRepeat = this.twoNoRepeat(service, subjectData.getTwoSubjectName(), parentId);
            if (twoNoRepeat==null){
                twoNoRepeat = new EduSubject();
                twoNoRepeat.setTitle(subjectData.getTwoSubjectName());
                twoNoRepeat.setParentId(parentId);
                service.save(twoNoRepeat);
            }
        }

    }

    // 判断一级分类不能重复添加
    private EduSubject oneNoRepeat(EduSubjectService service,String name){

        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");

        EduSubject eduSubject = service.getOne(wrapper);

        return eduSubject;

    }

    // 判断二级分类不能重复添加
    private EduSubject twoNoRepeat(EduSubjectService service,String name,String parentId){

        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",parentId);

        EduSubject eduSubject = service.getOne(wrapper);

        return eduSubject;

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
